package com.weixin.base.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.weixin.base.service.MessageService;
import com.weixin.base.util.Tools;

@Controller
public class WmtqAction {

	// 与接口配置信息中的Token要一致
//	private static String token = "ceshitoken";
	private static int userId = 127;

	@Autowired
	private MessageService messageService;

	/**
	 * 确认请求来自微信服务器
	 */
	@RequestMapping(value = "/mtq.do", method = RequestMethod.GET)
	public void ceshiGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException {

		System.out.println("ceshi-GET");

		// 微信加密签名
		String signature = Tools.convertRs(request.getParameter("signature"));
		// 时间戳
		String timestamp = Tools.convertRs(request.getParameter("timestamp"));
		// 随机数
		String nonce = Tools.convertRs(request.getParameter("nonce"));
		// 随机字符串
		String echostr = Tools.convertRs(request.getParameter("echostr"));

		String token=messageService.selectToken(userId);
System.out.println(token);
		PrintWriter out = response.getWriter();
		// 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
		if (Tools.checkSignature(signature, timestamp, nonce, token)) {
			out.print(echostr);
			System.out.println("1");
		}
		System.out.println("2");
		out.close();
		out = null;

		// 返回指令
		// response.setCharacterEncoding("UTF-8");
		// response.setContentType("text/plain");
		// response.getWriter().print(userAgent);
	}

	@RequestMapping(value = "/mtq.do", method = RequestMethod.POST)
	public void ceshiPost(HttpServletRequest request, HttpServletResponse response)
			throws IOException {

		System.out.println("ceshi-POST");
		// 将请求、响应的编码均设置为UTF-8（防止中文乱码）
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		// 调用核心业务类接收消息、处理消息
		String respMessage = messageService.processRequest(request,userId);

		// 响应消息
		PrintWriter out = response.getWriter();
		out.print(respMessage);
		out.close();
	}
}